package com.hoolai.qps.codes.netty.client;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;

import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.Message;
import com.google.protobuf.Message.Builder;
import com.hoolai.synroom.config.CmdsConfig;

public class ClientDecoder extends OneToOneDecoder {

    private final CmdsConfig CMDS_CONFIG;

    private static final Logger logger = Logger.getLogger(ClientDecoder.class);

    public ClientDecoder() {
        this.CMDS_CONFIG = new CmdsConfig("cmd/reqCMD.xml", "cmd/respCMD.xml", logger);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
        ChannelBuffer buffer = (ChannelBuffer) msg;
        int cmdId = buffer.readInt();
        int channelId = buffer.readInt();
        System.err.println("decode cmdId=" + cmdId + " ,channelId=" + channelId);
        byte[] bytes = new byte[buffer.readableBytes()];
        buffer.readBytes(bytes);
        Class<?> clazz = Class.forName(CMDS_CONFIG.getRespString(cmdId));
        
        
        //MethodAccess methodAccess = MethodAccess.get(clazz);
        
        Method method = clazz.getDeclaredMethod("getDefaultInstance");
        method.setAccessible(true);
        GeneratedMessage message = (GeneratedMessage) method.invoke(null);
        Builder builder = message.newBuilderForType().mergeFrom(bytes);
        Message proto = builder.build();
        //System.out.println(proto);
        return proto;
    }

}
